Page({
  data: {
    currentTeam: {},
    teams: [],
    filteredTeams: [],
    recentPhrases: [],
    teamNotifications: [],
    stats: {
      myPhrases: 0,
      teamPhrases: 0
    },
    showTeamSelector: false,
    showAddMenu: false,
    searchQuery: '',
    teamSearchQuery: ''
  },

  onLoad() {
    // 获取应用实例
    this.app = getApp();
    
    // 注册团队切换回调
    if (this.app.registerTeamSwitchCallback) {
      this.app.registerTeamSwitchCallback(this.onTeamSwitched.bind(this));
    }
    
    // 初始化数据
    this.loadData();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadData();
  },
  
  // 加载页面数据
  loadData() {
    // 获取当前团队
    const currentTeam = this.app.getCurrentTeam() || {};
    
    // 获取所有团队
    const teams = wx.getStorageSync('teams') || [];
    // 为团队添加成员数量属性（实际项目中应从接口获取）
    const teamsWithMemberCount = teams.map(team => ({
      ...team,
      memberCount: team.members ? team.members.length : 0
    }));
    
    // 获取最近使用的话术
    const phrases = wx.getStorageSync('phrases') || [];
    const recentPhrases = phrases
      .filter(phrase => phrase.teamId === currentTeam.id)
      .sort((a, b) => new Date(b.lastUsedTime || 0) - new Date(a.lastUsedTime || 0))
      .slice(0, 3);
    
    // 获取团队动态
    const teamNotifications = this.getTeamNotifications(currentTeam.id);
    
    // 计算统计数据
    const userInfo = wx.getStorageSync('userInfo') || {};
    const myPhraseCount = phrases.filter(phrase => phrase.creatorId === userInfo.id).length;
    const teamPhraseCount = phrases.filter(phrase => phrase.teamId === currentTeam.id).length;
    
    this.setData({
      currentTeam,
      teams: teamsWithMemberCount,
      filteredTeams: teamsWithMemberCount,
      recentPhrases,
      teamNotifications,
      stats: {
        myPhrases,
        teamPhrases
      }
    });
  },
  
  // 模拟获取团队动态
  getTeamNotifications(teamId) {
    // 实际项目中应从服务器获取
    return [
      {
        id: '1',
        userName: '张三',
        content: '添加了新话术 "产品介绍话术"',
        time: '10分钟前'
      },
      {
        id: '2',
        userName: '李四',
        content: '创建了新分组 "销售话术"',
        time: '1小时前'
      },
      {
        id: '3',
        userName: '王五',
        content: '加入了团队',
        time: '昨天'
      }
    ];
  },
  
  // 团队切换回调
  onTeamSwitched(teamId) {
    this.loadData();
  },
  
  // 显示团队选择器
  showTeamSelector() {
    this.setData({
      showTeamSelector: true,
      teamSearchQuery: ''
    });
  },
  
  // 隐藏团队选择器
  hideTeamSelector() {
    this.setData({
      showTeamSelector: false
    });
  },
  
  // 阻止事件冒泡
  stopPropagation(e) {
    e.stopPropagation();
  },
  
  // 选择团队
  selectTeam(e) {
    const teamId = e.currentTarget.dataset.id;
    if (this.app.switchTeam) {
      this.app.switchTeam(teamId);
    }
    this.hideTeamSelector();
  },
  
  // 团队搜索
  onTeamSearchInput(e) {
    const query = e.detail.value.trim().toLowerCase();
    const filteredTeams = this.data.teams.filter(team => 
      team.name.toLowerCase().includes(query)
    );
    
    this.setData({
      teamSearchQuery: query,
      filteredTeams
    });
  },
  
  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchQuery: e.detail.value
    });
    
    // 实际项目中可以在这里实现实时搜索
    if (e.detail.value.length > 0) {
      // 执行搜索逻辑
    }
  },
  
  // 显示添加菜单
  showAddMenu() {
    this.setData({
      showAddMenu: !this.data.showAddMenu
    });
  },
  
  // 导航到创建话术
  navigateToCreatePhrase() {
    this.setData({ showAddMenu: false });
    wx.navigateTo({
      url: '/pages/phrase/phrase-edit'
    });
  },
  
  // 导航到创建分组
  navigateToCreateGroup() {
    this.setData({ showAddMenu: false });
    wx.navigateTo({
      url: '/pages/phrase/group-management?action=create'
    });
  },
  
  // 导航到创建团队
  navigateToCreateTeam() {
    this.setData({ showAddMenu: false, showTeamSelector: false });
    wx.navigateTo({
      url: '/pages/team/team-create'
    });
  },
  
  // 导航到加入团队
  navigateToJoinTeam() {
    this.setData({ showTeamSelector: false });
    wx.navigateTo({
      url: '/pages/team/team-join'
    });
  },
  
  // 导航到团队管理
  navigateToTeamManagement() {
    wx.navigateTo({
      url: '/pages/team/team-list'
    });
  },
  
  // 导航到公共话术
  navigateToPublicPhrases() {
    wx.navigateTo({
      url: '/pages/public/public-phrases'
    });
  },
  
  // 导航到所有话术
  goToAllPhrases() {
    wx.navigateTo({
      url: '/pages/phrase/phrase-library'
    });
  },
  
  // 导航到我的话术
  goToMyPhrases() {
    wx.navigateTo({
      url: '/pages/phrase/my-phrases'
    });
  },
  
  // 导航到设置
  goToSettings() {
    wx.navigateTo({
      url: '/pages/settings/settings'
    });
  },
  
  // 显示通知
  showNotifications() {
    wx.navigateTo({
      url: '/pages/notifications/notifications'
    });
  },
  
  // 复制话术
  copyPhrase(e) {
    const phraseId = e.currentTarget.dataset.id;
    const phrase = wx.getStorageSync('phrases').find(p => p.id === phraseId);
    
    if (phrase) {
      wx.setClipboardData({
        data: phrase.content,
        success() {
          wx.showToast({
            title: '已复制',
            icon: 'success',
            duration: 1500
          });
        }
      });
    }
  },
  
  // 导航到话术详情
  navigateToPhraseDetail(e) {
    const phraseId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/phrase/phrase-detail?id=${phraseId}`
    });
  }
})
    